// Copyright (C) 2005 Taylor L. Riché <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// 	$Id: CourierUnit.cc 130 2005-08-13 04:27:07Z richetl $	
//

#include "CourierUnit.hh"

using namespace lee;

CourierUnit::CourierUnit(std::map<pthread_t, lee::CourierUnit *> & cmap,
			 Scheduler * s) : eventList(NULL),
					  sched(s)
{
  MethodWrapper<CourierUnit> * mw = new MethodWrapper<CourierUnit>;
  mw->object = this;
  mw->method = &CourierUnit::process;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  if(pthread_create(&coreThread, &attr, plainFunctionCU, (void *)mw)) {
    std::cerr << "pthread_create failed" << std::endl;
    std::exit(1);
  }
  cmap[coreThread] = this;
  s->registerCourier(this);
}

void
CourierUnit::process()
{
  Synchronized::Scope mutex(this);
  while(masterSub == NULL) {
    wait();
  }
  while(true) {
    EventWrapper * currWrapper = eventQueue.pop();
    Event * currEvent = currWrapper->ev;
    Subscription * currSub = currWrapper->master;
    delete currWrapper;
    if(currSub == NULL) {
      currSub = masterSub;
    }
    eventList = new std::list<Event *>;
    currSub->deliver_wrapper(currEvent);
    for(std::list<Event *>::iterator i = eventList->begin();
	i != eventList->end(); i++) {
      EventWrapper * newWrapper = new EventWrapper;
      newWrapper->master = currSub;
      newWrapper->ev = *i;
      sched->getCU()->deliver(newWrapper);
    }
  }
  return;
}

std::list<Event *> * const
CourierUnit::getList() const
{
  return eventList;
}

